# -*- coding: utf-8 -*-
# @Time : 2021/10/21 4:34 下午
# @Author : HL
# @Email : 1277078753@qq.com
# @Describe :
import configparser
import os

from applications.extensions import db
from applications.models import Trade
from web3 import Web3
from applications.common.nft.scripts.jy import nft_trade

path = os.getcwd() + r"/env.ini"
config = configparser.ConfigParser()
config.read(path)


def validate_trade(trade_address, item, network):
    if item == 'nft':
      return validate_trade_nft(trade_address, item, network)
    else:
        return False, "没有该项目"


def validate_trade_nft(trade_hx, item, network):
    # tudo 没写合约判断
    try:
        url = config.get('network',network)
    except:
        return False, "没有该网络"
    _our_address = config.get('contract', "our_address")
    _trade_number = config.get('contract', "trade_number")
    try:
        w3 = Web3(Web3.HTTPProvider(url))
        tx0 = w3.eth.getTransactionReceipt(trade_hx)
        tx = w3.eth.getTransaction(trade_hx)
    except:
        return False, "验证交易有误"
    our_address = tx0["to"]
    succ = tx0["status"]
    trade_address = tx0["from"]
    trade_number = tx["value"]/1000000000000000000
    if trade_number == 0 or _trade_number != trade_number:
        return False, "转账数量不对"
    else:
        if our_address == _our_address and succ == 1:
            hx = nft_trade(trade_address)
            if hx == 0:
                return False, "合约地址为空值,NFT铸造或交易失败！"
            else:
                trade = Trade(
                    trade_address=trade_address,
                    item=item
                )
                r = db.session.add(trade)
                db.session.commit()
                return True, hx
        else:
            return False, "转账地址错误"


# def validate_trade_nft(trade_address, item, network):
#     hx = nft_trade(trade_address)
#     if hx == 0:
#         return False, "合约地址为空值,NFT铸造或交易失败！"
#     else:
#         trade = Trade(
#             trade_address=trade_address,
#             item=item
#         )
#         r = db.session.add(trade)
#         db.session.commit()
#         return True, hx
#


def toChecksumAddress(s: str):
    try:
        return Web3.toChecksumAddress(s)
    except:
        return None
